package leetcode;

/**
 * 描述:33. 搜索旋转排序数组
 *
 * @author Madison You
 * @created 23:06
 */
public class Mid_33_Search {

    public static void main(String[] args) {
        int[] ints = {4, 5, 6, 7, 0, 1, 2};
        int search = new Mid_33_Search().search(ints, 3);
        System.out.println(search);
    }

    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            /*二分查找总有一边是有序的*/
            /*这启示我们可以在常规二分查找的时候查看当前 mid 为分割位置分割出来的两个部分 [l, mid] 和 [mid + 1, r] 哪个部分是有序的*/
            if (nums[left] <= nums[mid]) {
                if (nums[left] <= target && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                if (nums[mid] < target && target <= nums[nums.length-1]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }

}
